﻿Imports System.ComponentModel.Composition
Imports System.Net

<ExportCompent(GetType(IInfoSender), "Twitter", "d72512d4-c553-4b34-a594-13c98379e1be", "1.0.0.1")>
Public Class TwitterSender
    Inherits InfoSenderBase

    Private TS As TwitterOAuth
    Private SW As SettingWindow

    Public Overrides Function GetAvailability() As Boolean
        If My.Settings.UseOAuth Then
            If String.IsNullOrEmpty(My.Settings.Token) OrElse String.IsNullOrEmpty(My.Settings.TokenSecret) Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If
    End Function

    Public Overrides Sub SendInfo(message As String)
        Try
            TS.Update(message)
        Catch ex As Exception

        End Try
    End Sub

    Public Overrides Sub ShowSetting()
        SW = New SettingWindow
        SW.ShowDialog()
        SW = Nothing
        TS.AddToken(My.Settings.Token, My.Settings.TokenSecret)
    End Sub

    Public Overrides Sub ShutDown()
        My.Settings.Save()
    End Sub

    Public Overrides Sub StartUp()
        If Not HasToken() Then
            TS = New TwitterOAuth(ComsumerKey, ComsumerSecret)
        Else
            TS = New TwitterOAuth(ComsumerKey, ComsumerSecret, My.Settings.Token, My.Settings.TokenSecret)
        End If
        AddHandler My.Settings.PropertyChanged, AddressOf PropertyChangeMonitor
    End Sub

    Private Function HasToken() As Boolean
        Return Not (String.IsNullOrEmpty(My.Settings.Token) OrElse String.IsNullOrEmpty(My.Settings.TokenSecret))
    End Function

    Private Sub PropertyChangeMonitor(sender As Object, e As ComponentModel.PropertyChangedEventArgs)
        If e.PropertyName = "ProxyType" OrElse
           e.PropertyName = "ProxyURL" OrElse
           e.PropertyName = "ProxyUsername" OrElse
           e.PropertyName = "ProxyPassword" OrElse
           e.PropertyName = "ProxyPort" Then
            Try
                If My.Settings.ProxyType = 0 Then
                    WebRequest.DefaultWebProxy = Nothing
                ElseIf My.Settings.ProxyType = 1 Then
                    If String.IsNullOrEmpty(My.Settings.ProxyURL) Then
                        WebRequest.DefaultWebProxy = New WebProxy(My.Settings.ProxyURL, My.Settings.ProxyPort)
                        If Not (String.IsNullOrEmpty(My.Settings.ProxyUsername) AndAlso String.IsNullOrEmpty(My.Settings.ProxyPassword)) Then
                            WebRequest.DefaultWebProxy.Credentials = New NetworkCredential(My.Settings.ProxyUsername, My.Settings.ProxyPassword)
                        End If
                    End If
                Else
                    WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy
                End If
            Catch ex As Exception

            End Try
        End If
    End Sub

End Class
